from common.api import http_result
from common.utils.time import current_timestamp, current_time_string
from developer_module.models import ConsoleLog, UserAction
from developer_module.rpc import developer_pb2_grpc


class LogHandler(developer_pb2_grpc.LogServicer):

    def do_query_log(self, param, session):
        page = int(param.get('page', 1))
        page_size = int(param.get('page_size', 15))
        offset = page_size * (page - 1)

        select = ConsoleLog.select().where(ConsoleLog.content.contains(param.get('condition')))
        if page == 1:
            count = select.count()
        else:
            count = 0
        logs = select.order_by(ConsoleLog.time.desc()).offset(offset).limit(page_size)
        result = []
        for log in logs:
            result.append({
                'time_str': log.time_str,
                'level': log.level,
                'content': log.content,
            })
        return self.resp(1, http_result.RESULT_SUCCESS, {
            'total': count,
            'data': result,
        })

    def do_open_log(self, param, session):
        from common.api.service_center import get_etcd_client
        client = get_etcd_client()
        client.set('developer_log_status', 'on')
        return self.resp(1, http_result.RESULT_SUCCESS)

    def do_close_log(self, param, session):
        from common.api.service_center import get_etcd_client
        client = get_etcd_client()
        client.set('developer_log_status', 'off')
        return self.resp(1, http_result.RESULT_SUCCESS)

    def do_clear_console_log(self, param, session):
        ConsoleLog.delete().execute()
        return self.resp(1, http_result.RESULT_SUCCESS)


def save_log(param):
    log = ConsoleLog()
    log.time = current_timestamp()
    log.time_str = current_time_string()
    log.content = param.get('content', '')
    log.level = param.get('level', '')
    log.save()


def save_user_action(param):
    action = UserAction()
    action.time = current_timestamp()
    action.time_str = current_time_string()
    action.req = param.get('req', '')
    action.resp = param.get('resp', '')
    action.user = param.get('user', '')
    action.save()
